package com.itheima.intercepter;

import com.alibaba.fastjson2.JSON;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangbaiyan
 * @date 2024-10-02 09:08
 * @description:
 * @version:
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override   //目标资源方法运行前运行,返回true:放行,放回false,不放行
    public boolean preHandle(HttpServletRequest req , HttpServletResponse res , Object handler) throws Exception {
//        System.out.println("preHandle");


        //1.获取请求url
        String url = req.getRequestURI().toString();
        log.info("请求的url:{}",url);
        //2.判断请求url是否包含login,如果包含,说明是登录操作,放行
        if(url.contains("login")){
            log.info("登录请求，放行");

            return true;
        }

        //3.获取请求头中的令牌
        String jwt = req.getHeader("token");

        //4.判断令牌是否存在,如果不存在,拦截
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头中无token,拦截");
            Result error = Result.error("NOT_LOGIN");
            res.getWriter().write(JSON.toJSONString(error));
            return false;
        }
        //5.解析token,如果解析失败,拦截
        try{
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("解析令牌失败,拦截");
            Result error = Result.error("NOT_LOGIN");
            res.getWriter().write(JSON.toJSONString(error));
            return false;
        }
        //放行
        log.info("令牌合法,放行");
        return true;

    }
    @Override   //目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }



    @Override   //视图渲染完毕后运行,最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
         System.out.println("afterCompletion");
    }
}
